<template>
  <div class="auth-container">
    <div class="auth-card">
      <h2 class="auth-title">用户登录</h2>
      <el-form :model="loginForm" label-width="80px">
        <el-form-item label="手机号">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-button type="primary" class="auth-btn" @click="handleLogin">登录</el-button>
      </el-form>
      <div class="auth-footer">
        <el-link type="primary" @click="goRegister">立即注册</el-link>
      
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from '@/utils/axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const loginForm = ref({  // 修正变量名为loginForm
  phone: '',
  password: ''
});

const handleLogin = async () => {
  try {
    const response = await axios.post('/auth/login', {
      phone: loginForm.value.phone,
      password: loginForm.value.password
    }, {
      headers: { 'Content-Type': 'application/json' },
      withCredentials: true
    });

    if (response.data.token) {
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('role', response.data.role);
      localStorage.setItem('username', response.data.username);
      localStorage.setItem('userId', response.data.userId); 
      localStorage.setItem('profileImage', response.data.profileImage);
      // 根据角色跳转不同页面
      if (response.data.role === 'ADMIN') {
        router.push('/admin/dashboard'); // 管理员仪表盘
      } else {
        router.push('/user/dashboard'); // 普通用户仪表盘
      }
      
      ElMessage.success('登录成功');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '登录失败');
  }
};

const goRegister = () => {
  router.push('/register');
}
</script>

  
<style scoped>
  .auth-container {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f0f2f5;
  }
  
  .auth-card {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .auth-title {
    text-align: center;
    margin-bottom: 30px;
    color: #303133;
  }
  
  .auth-btn {
    width: 100%;
    margin-top: 20px;
  }
  
  .auth-footer {
    margin-top: 30px;
    text-align: center;
  }
  
  .copyright {
    margin-top: 30px;
    color: #909399;
    font-size: 14px;
  }
  </style>